﻿using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

// 在文件顶部添加对login类的引用
using Mes;
using System.Net.Http;

namespace Mes.采购管理
{
    public partial class Details : Form
    {
        private string purchaseNo; // 采购编号
        private Mes.采购管理.model.Details purchaseDetail; // 采购详情数据模型

        // 添加构造函数，接收采购编号
        public Details(string purchaseNo)
        {
            InitializeComponent();
            this.purchaseNo = purchaseNo;
        }


        private void Details_Load(object sender, EventArgs e)
        {
            // 设置窗口状态为正常
            this.WindowState = FormWindowState.Normal;
            Console.WriteLine("窗体加载完成");
            dataDetails.AutoGenerateColumns = false; // 改为false，使用设计器中定义的中文列
            dataDetails.AllowUserToAddRows = false;
            dataDetails.ReadOnly = true;
            dataDetails.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 添加CellFormatting事件处理程序
            dataDetails.CellFormatting += dataDetails_CellFormatting;
            // 添加RowPostPaint事件处理程序，用于显示行号
            dataDetails.RowPostPaint += dataDetails_RowPostPaint;
            // 隐藏行标题区域（删除编号前面的那一列）
            dataDetails.RowHeadersVisible = false;
            // 加载采购详情数据
            LoadPurchaseDetailData();
        }

        // RowPostPaint事件处理程序，用于在编号列显示行号
        private void dataDetails_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            // 在编号列显示行号
            DataGridView dataGridView = sender as DataGridView;
            if (dataGridView == null) return;

            // 获取编号列的索引
            int serialColumnIndex = -1;
            foreach (DataGridViewColumn column in dataGridView.Columns)
            {
                if (column.Name == "serial")
                {
                    serialColumnIndex = column.Index;
                    break;
                }
            }
            if (serialColumnIndex == -1) return;

            // 设置行号的样式
            using (SolidBrush brush = new SolidBrush(dataGridView.DefaultCellStyle.ForeColor))
            {
                // 计算行号
                int rowNumber = e.RowIndex + 1;
                string rowNumberStr = rowNumber.ToString();

                // 绘制行号到编号列
                DataGridViewCell cell = dataGridView.Rows[e.RowIndex].Cells[serialColumnIndex];
                Rectangle cellBounds = dataGridView.GetCellDisplayRectangle(serialColumnIndex, e.RowIndex, false);
                SizeF size = e.Graphics.MeasureString(rowNumberStr, dataGridView.DefaultCellStyle.Font);

                e.Graphics.DrawString(rowNumberStr, dataGridView.DefaultCellStyle.Font, brush,
                    cellBounds.Left + (cellBounds.Width - size.Width) / 2, cellBounds.Top + (cellBounds.Height - size.Height) / 2);
            }
        }
        // CellFormatting事件处理程序，用于格式化单元格值
        private void dataDetails_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataDetails.Columns[e.ColumnIndex].Name == "Is_Final" && e.Value != null)
            {
                bool isFinal = (bool)e.Value;
                e.Value = isFinal ? "是" : "否"; // false表示没有下一个（否），true表示有下一个（是）
                e.FormattingApplied = true;
            }
        }

        private async void LoadPurchaseDetailData()
        {
            try
            {
                // 使用传入的采购编号请求数据
                string apiUrl = $"http://10.223.8.9:8082/api/Purchase/GetApprovalDetail?Reqest_No={purchaseNo}";
                Console.WriteLine("请求API: " + apiUrl);
        
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "utf-8");
                    client.Timeout = TimeSpan.FromSeconds(10);
                    
                    // 添加Token认证头
                    if (!string.IsNullOrEmpty(login.CurrentToken))
                    {
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    }
        
                    // 发送GET请求
                    HttpResponseMessage response = await client.GetAsync(apiUrl);
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("API响应:\n" + jsonResponse);
        
                    JObject jsonObject = JObject.Parse(jsonResponse);
        
                    if (jsonObject["code"]?.Value<int>() == 200 && jsonObject["data"] != null)
                    {
                        // 解析采购详情数据
                        purchaseDetail = jsonObject["data"].ToObject<Mes.采购管理.model.Details>();
        
                        if (purchaseDetail != null)
                        {
                            // 绑定采购信息到文本框
                            textReqest_No.Text = purchaseDetail.Reqest_No;
                            textMaterlal_Id.Text = purchaseDetail.Materlal_Id;
                            textMatelal_name.Text = purchaseDetail.Matelal_name;
                            textRequest_Qty.Text = purchaseDetail.Request_Qty.ToString();
                            textRequest_Ddte.Text = purchaseDetail.Request_Ddte.ToString("yyyy-MM-dd");
                            textStatus.Text = purchaseDetail.Status;
                            textApproval.Text = purchaseDetail.Approval;
                            textBudget_Amount.Text = purchaseDetail.Budget_Amount.ToString();
        
                            // 绑定审批记录到数据表格
                            dataDetails.DataSource = null;
                            if (purchaseDetail.ApprovalRecords != null && purchaseDetail.ApprovalRecords.Count > 0)
                            {
                                dataDetails.DataSource = purchaseDetail.ApprovalRecords;
                            }
                            else
                            {
                                MessageBox.Show("没有找到审批记录数据", "提示");
                            }
                        }
                        else
                        {
                            MessageBox.Show("解析数据失败", "提示");
                        }
                    }
                    else
                    {
                        MessageBox.Show($"API返回错误: {jsonObject["message"]?.Value<string>() ?? "未知错误"}", "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误");
            }
        }
    }
}
